package net.mihome.app.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.adapter.GoodsAdapter;
import net.mihome.app.bean.Goods;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.maxwin.view.XListView;

public class MihomeGoodsView extends XListView {

    protected static final String STATE_PAUSE_ON_SCROLL = "STATE_PAUSE_ON_SCROLL";
    protected static final String STATE_PAUSE_ON_FLING = "STATE_PAUSE_ON_FLING";
    protected boolean pauseOnScroll = false;
    protected boolean pauseOnFling = true;
	private GoodsAdapter adapter;
	private List<Goods> listData=new ArrayList<Goods>();
	Handler handler;
	private AppContext appContext;
	private int begin=0;
	private int num=10;
	private MyViewLinster myViewLinster;
    private ImageLoader imageLoader;
    public MihomeGoodsView(Context context) {
        super(context);
        afterInit();
        // TODO Auto-generated constructor stub
    }
	public MihomeGoodsView(Context context, AttributeSet attrs) {
		super(context, attrs);
		afterInit();
		// TODO Auto-generated constructor stub
	}
	public MihomeGoodsView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		afterInit();
		// TODO Auto-generated constructor stub
	}
	@SuppressLint("NewApi")
	public void afterInit(){
        imageLoader= ImageLoader.getInstance();
        setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
		adapter = new GoodsAdapter(getContext(),R.layout.goods_listitem, listData,imageLoader,new MyViewLinster() {
            @Override
            public void onLoadComplete() {
                if(myViewLinster!=null){
                    myViewLinster.onLoadComplete();
                }
            }

            @Override
            public void onBeforeLoad() {

            }
        });
		setAdapter(adapter);
        setPullLoadEnable(true);
        setPullRefreshEnable(true);
		appContext=(AppContext) getContext().getApplicationContext();
//		setOnItemClickListener(new OnItemClickListener() {
//			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//				Goods goods = (Goods) view.getTag();
//                Toast.makeText(getContext(),"这事跳转到商品详情"+goods.getDesc(),Toast.LENGTH_SHORT).show();
//			}
//		});
		handler=new Handler(new Handler.Callback() {
			@Override
			public boolean handleMessage(Message arg0) {
				adapter.notifyDataSetChanged();
				if(myViewLinster!=null){
					myViewLinster.onLoadComplete();
				}
				return false;
			}
		});
        setXListViewListener(new IXListViewListener() {
            @Override
            public void onRefresh() {
                initData(false);
            }

            @Override
            public void onLoadMore() {
                initData(true);
            }
        });
	}

	public void initData(final boolean isMore){
		if(myViewLinster!=null){
			myViewLinster.onBeforeLoad();
		}
        if(isMore){
            begin=(begin+1)*num;
        }else{
            begin=0;
        }
		num=10;
		RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
		requestParams.add("begin",begin+"");
		requestParams.add("num",num+"");
		appContext.ASYNC_HTTP_CLIENT.get(URLs.MIHOME_GET_GOODS,requestParams,new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<Goods> list=Goods.parseList(responsePojo.getData());
                if(list!=null&&!list.isEmpty()){
                    if(!isMore){
                        listData.clear();
                        listData.addAll(list);
                    }else{
                        listData.addAll(list);
                    }
                    adapter.notifyDataSetChanged();
                }
                stopRefresh();
                stopLoadMore();
                setRefreshTime("不久前");
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(getContext(),"网络异常，请稍后再试",Toast.LENGTH_LONG).show();
                stopRefresh();
                stopLoadMore();
                setRefreshTime("不久前");
            }
        });
	}
	public MyViewLinster getMyViewLinster() {
		return myViewLinster;
	}
	public void setMyViewLinster(MyViewLinster myViewLinster) {
		this.myViewLinster = myViewLinster;
	}
	
}
